from bs4 import BeautifulSoup
import requests
import re


class spiderWord(object):
    """
    同义词收集
    """
    def __init__(self):
        self.headers = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,"
                      "*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Host": "kmcha.com",
            "Pragma": "no-cache",
            "sec-ch-ua": '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
            "sec-ch-ua-mobile": "?0",
            "Sec-Fetch-Dest": "document",
            "Sec-Fetch-Mode": "navigate",
            "Sec-Fetch-Site": "same-origin",
            "Sec-Fetch-User": "?1",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/92.0.4515.131 Safari/537.36"}
        self.main_url = "https://kmcha.com/similar/"

    def single(self, word: str) -> list:
        """
        获取单个同义词
        :param word: 待查询的词语
        :return: 同义词列表
        """
        content = requests.get(self.main_url + word, headers=self.headers).text
        soup = BeautifulSoup(content, 'lxml')
        text = ''
        for element in soup.find_all(class_="container"):
            text = str(element.get_text())
        start = end = 0
        text = text.split("\t")
        for i, element in enumerate(text):
            if element.find("的相似词") != -1:
                start = i
            if element.find("相关查询") != -1:
                end = i
        text = text[start:end]
        my_word = []
        for element in text:
            for element_one in element.split("\n"):
                element_one = re.sub("\r|\t|\xa0| |\n", "", element_one)
                temp = element_one.split("\n")
                if temp != [""]:
                    temp = temp[0]
                    if not re.findall("的相似词|-百科全书|相似词查询|查询", temp):
                        my_word.append(temp)
        return my_word


if __name__ == '__main__':
    spiderWord = spiderWord()
    word_ = spiderWord.single("分娩期")
    print(word_)
